package com.mic.controller;

import com.mic.pojo.*;
import com.mic.service.AdminServiceImpl;
import com.mic.service.UserServiceImpl;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class UserController {

    @Autowired
    @Qualifier("AdminServiceImpl")
    AdminServiceImpl adminService;

    @Autowired
    @Qualifier("UserServiceImpl")
    UserServiceImpl userService;

    @RequestMapping("/updateUser")
    public void updateUser(MultipartFile profilePhoto, @Param("nickname")String nickname,
                           @Param("introduce")String introduce, @Param("sex") String sex, @Param("birthday")Date birthday,
                           @Param("realName") String realName, @Param("password")String password, HttpSession session, HttpServletRequest request,
                           HttpServletResponse response, Model model) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");
        User user = adminService.queryUserByUserId(userId);

        //设置个人基本信息
        user.setNickname(nickname);
        user.setIntroduce(introduce);
        user.setSex(sex);
        user.setBirthday(birthday);
        user.setRealName(realName);
        user.setPassword(password);

        //这个RequestParam(value="file")的是我们在jsp的name=“file”
        // 使用UUID给图片重命名，并去掉四个“-”
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取文件的扩展名
        String ext = FilenameUtils.getExtension(profilePhoto.getOriginalFilename());
        // 设置图片上传路径
        //String url = request.getSession().getServletContext().getRealPath("/img");
        String url = "F:\\JAVASPRING\\microBlog\\microblog\\src\\main\\webapp\\img";
        System.out.println(url);
        // 以绝对路径保存重名命后的图片
        profilePhoto.transferTo(new File(url + "/" + name + "." + ext));
        // 把图片存储路径保存到数据库
        user.setProfilePhoto("img/" + name + "." + ext);
        userService.updatePersonalInfo(user);

        response.sendRedirect(request.getContextPath()+"/toUserPersonalPage");

    }



    @RequestMapping("/like")
    public void like(HttpServletResponse response, HttpServletRequest request,
                     HttpSession session,Integer certainArticleId) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");
        Article article = userService.queryArticleByArticleId(certainArticleId);
        article.setLikes(article.getLikes()+1);
        userService.updateArticle(article);

        response.sendRedirect(request.getContextPath()+"/toArticlePage?certainArticleId="+certainArticleId);

    }

    @RequestMapping("/addComment")
    public void addComment(HttpServletResponse response, HttpServletRequest request, HttpSession session, Integer articleId,
                           @Param("userComment") String text, Integer certainArticleId, Timestamp time
                           ) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");

        User user = adminService.queryUserByUserId(userId);

        Comment comment = new Comment();
        comment.setText(text);
        comment.setArticleId(certainArticleId);
        comment.setUserId(user);
        comment.setTime(time);
        userService.addComment(comment);

        response.sendRedirect(request.getContextPath()+"/toArticlePage?certainArticleId="+certainArticleId);
    }

    @RequestMapping("/subscription")
    public void subscription(HttpServletResponse response, HttpServletRequest request,
                             HttpSession session,Integer certainUserId) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");

        UserSubscription userSubscription = new UserSubscription();
        userSubscription.setUserId(userId);
        userSubscription.setSubscriptionId(certainUserId);

        userService.addSubscription(userSubscription);

        response.sendRedirect(request.getContextPath()+"/toOthersPersonalPage?certainUserId="+certainUserId);
    }

    @RequestMapping("/cancelSubscription")
    public void cancelSubscription(HttpServletResponse response, HttpServletRequest request,
                                   HttpSession session,Integer certainUserId) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");
        List<UserSubscription> userSubscriptions = userService.queryAllUserSubscriptionByUserId(userId);
        for(UserSubscription userSubscription:userSubscriptions){
            if (userSubscription.getSubscriptionId().equals(certainUserId))
                userService.cancelSubscription(userSubscription);
        }

        response.sendRedirect(request.getContextPath()+"/toOthersPersonalPage?certainUserId="+certainUserId);

    }

    @RequestMapping("/favorite")
    public void favorite(HttpServletResponse response, HttpServletRequest request,
                         HttpSession session,Integer certainArticleId) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");

        UserFavorite userFavorite1 = new UserFavorite();
        userFavorite1.setUserId(userId);
        userFavorite1.setArticleId(certainArticleId);

        userService.addFavorite(userFavorite1);

        /*List<UserFavorite> userFavorites = userService.queryAllUserFavoriteByUserId(userId);
        for (UserFavorite userFavorite:userFavorites) {
            if (userFavorite.getArticleId().equals(certainArticleId))
                response.sendRedirect(request.getContextPath() + "/toArticlePage?certainArticleId=" + certainArticleId);
            else {
                UserFavorite userFavorite1 = new UserFavorite();
                userFavorite1.setUserId(userId);
                userFavorite1.setArticleId(certainArticleId);

                userService.addFavorite(userFavorite1);
            }
        }*/
        response.sendRedirect(request.getContextPath()+"/toArticlePage?certainArticleId="+certainArticleId);
    }

    @RequestMapping("/cancelFavorite")
    public void cancelFavorite(HttpServletResponse response, HttpServletRequest request,
                               HttpSession session,Integer certainArticleId) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");
        List<UserFavorite> userFavorites = userService.queryAllUserFavoriteByUserId(userId);

        for(UserFavorite userFavorite:userFavorites) {
            if (userFavorite.getArticleId().equals(certainArticleId))
                userService.cancelFavorite(userFavorite);
        }

        // response.sendRedirect(request.getContextPath()+"/toArticlePage?certainArticleId="+certainArticleId);
         response.sendRedirect(request.getContextPath()+"/toUserFavorite");


    }

    @RequestMapping("/writeAnArticle")
    public void writeAnArticle(HttpServletResponse response, HttpServletRequest request, HttpSession session,
                               String title, String text, MultipartFile img, Timestamp publishTime
    ) throws IOException {
        Integer userId = (Integer) session.getAttribute("userId");
        User user = adminService.queryUserByUserId(userId);

        Article article = new Article();
        article.setUser(user);
        article.setBlogId(userId);
        article.setTitle(title);

        //这个RequestParam(value="file")的是我们在jsp的name=“file”
        // 使用UUID给图片重命名，并去掉四个“-”
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取文件的扩展名
        String ext = FilenameUtils.getExtension(img.getOriginalFilename());
        // 设置图片上传路径
        //String url = request.getSession().getServletContext().getRealPath("/img");
        String url = "F:\\JAVASPRING\\microBlog\\microblog\\src\\main\\webapp\\img";
        System.out.println(url);
        // 以绝对路径保存重名命后的图片
        img.transferTo(new File(url + "/" + name + "." + ext));
        // 把图片存储路径保存到数据库
        article.setImg("img/" + name + "." + ext);
        article.setInShort(userService.getInShort(text));
        article.setPublishTime(publishTime);
        article.setContent(text);

        userService.writeAnArticle(article);
        response.sendRedirect(request.getContextPath()+"/toUserPersonalPage");
    }

    @RequestMapping("/deleteAnArticle")
    public void deleteAnArticle(HttpServletResponse response, HttpServletRequest request,
                                HttpSession session,Integer certainArticleId) throws IOException {
        userService.deleteAnArticle(certainArticleId);
        response.sendRedirect(request.getContextPath()+"/toBlogSquare");
    }

    @RequestMapping("/deleteACommentId")
    public void deleteACommentId(HttpServletResponse response, HttpServletRequest request,
                                HttpSession session,Integer commentId) throws IOException {
        Comment comment = userService.getCommentById(commentId);
        int articleId = comment.getArticleId();
        userService.deleteACommentId(commentId);

        //response.sendRedirect(request.getContextPath()+"/toArticlePage");
        response.sendRedirect(request.getContextPath()+"/toArticlePage?certainArticleId="+articleId);
    }


    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {

        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }
}
